#import "MRTableViewCell.h"

@implementation MRTableViewCell
{
	UITapGestureRecognizer		*_tapGestureRecognizer;
	MRTabelViewCellHandler		_handler;
}

/*===================================================================
 说明:
    初始化
 ==================================================================*/
- (void)awakeFromNib
{
    [super awakeFromNib];
    
    _title = [[MRLabel alloc] init];
	_title.tag = MRSkinColorMainText;
	_title.font = [UIFont boldSystemFontOfSize:17];
	_title.textAlignment = NSTextAlignmentCenter;
}

- (void)didLanguage
{
	self.textLabel.text = L(self.language);
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
	if (newSuperview == nil) [self cancel];
	[super willMoveToSuperview:newSuperview];
}

- (void)done
{
	UITableView *view = (UITableView *)self.superview;
	while (view && ![view isKindOfClass:[UITableView class]])
	{
		view = (UITableView *)view.superview;
	}
	
	if (view)
	{
		id delegate = view.delegate;
		if ([delegate respondsToSelector:@selector(didDoneCell:indexPath:)])
		{
			[delegate didDoneCell:self indexPath:[view indexPathForCell:self]];
		}
	}
	
	[self cancel];
}

- (void)cancel
{
	[_tapGestureRecognizer.view removeGestureRecognizer:_tapGestureRecognizer];
    [self resignFirstResponder];
}

/*===================================================================
 说明:
    输入视图
 ==================================================================*/
- (MRPickerView *)inputView
{
	if (!_inputView)
	{
		UIToolbar *bar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 44)];
		[bar setBackgroundImage:[UIImage new] forToolbarPosition:UIBarPositionTop barMetrics:UIBarMetricsDefault];
		
		//按钮
		UIBarButtonItem *cancel = [UIBarButtonItem initWithTitle:@"Cancel" target:self action:@selector(cancel)];
		cancel.language = @"IDS_CANCEL";
		UIBarButtonItem *middle = [UIBarButtonItem initWithSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
		UIBarButtonItem *done   = [UIBarButtonItem initWithTitle:@"Done" target:self action:@selector(done)];
		done.language   = @"IDS_DONE";
		
		[bar setItems:@[cancel, middle, done]];
		bar.backgroundColor = rgba(127, 127, 127, .05);
		
		//标题
		[_title addConstraintEqualSuperview:bar];
		_inputView = [[MRPickerView alloc] initWithBar:bar];
	}
	
	[_tapGestureRecognizer.view removeGestureRecognizer:_tapGestureRecognizer];
	
	_tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancel)];
	_tapGestureRecognizer.numberOfTouchesRequired = 1;
	[[UIApplication sharedApplication].keyWindow addGestureRecognizer:_tapGestureRecognizer];
	
	return _inputView;
}

- (BOOL)becomeFirstResponder
{
	_title.text = self.textLabel.text;
	return [super becomeFirstResponder];
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

@end
